<template>
	<scroll-view 
		class="points-container" 
		scroll-y="true" 
		refresher-enabled="true" 
		:refresher-triggered="refresherTriggered" 
		@refresherrefresh="onRefresh"
		@refresherrestore="onRestore"
	>
		<!-- 用户积分概览 -->
		<UserPointsOverview :user="user" :userAdditionalInfo="userAdditionalInfo" @refresh="handleRefresh"
			@checkin="handleCheckIn" />

		<!-- 积分统计卡片 -->
		<PointsStatsCards :totalPoints="userAdditionalInfo.totalPoints || 0"
			:currentPoints="userAdditionalInfo.currentPoints || 0" :memberLevel="userAdditionalInfo.memberLevel || 0" />

		<!-- 积分变动记录 -->
		<PointsChangeHistory :userId="user.userId" :pointsChangeRecords="pointsChangeRecords" :loading="loading"
			:hasMore="hasMore" :isExpanded="isExpanded" @load-more="handleLoadMore" @refresh="handleRefreshHistory"
			@toggle-expand="handleToggleExpand" @filter-change="handleFilterChange" />

		<!-- 积分获取指南 -->
		<PointsGuide />

		<!-- 积分商城 -->
		<!-- <PointsMall /> -->
	</scroll-view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed } from 'vue'
	import { getUserPointsInfo, getPointsChangeRecordDetail, userCheckIn, type PointsChangeRecord } from '@/api/point/point'
	import useUserStore from '@/store/modules/user'
	import UserPointsOverview from './components/UserPointsOverview.vue'
	import PointsStatsCards from './components/PointsStatsCards.vue'
	import PointsChangeHistory from './components/PointsChangeHistory.vue'
	import PointsGuide from './components/PointsGuide.vue'
	import PointsMall from './components/PointsMall.vue'

	const userStore = useUserStore()
	const user = ref(userStore.user)
	const userAdditionalInfo = ref(userStore.userAdditionalInfo)
	const pointsChangeRecords = ref<PointsChangeRecord[]>([])
	const loading = ref(false)
	const hasMore = ref(true)
	const isExpanded = ref(false)
	const currentPage = ref(1)
	const pageSize = ref(5)
	const totalCount = ref(0)
	const currentFilterType = ref(1) // 1-全部记录 2-收入 3-支出
	// 下拉刷新状态
	const refresherTriggered = ref(false)

	// 获取用户积分变动记录
	const fetchPointsHistory = async (page = 1, reset = false, type = currentFilterType.value) => {
		if (!user.value.userId) return

		try {
			loading.value = true
			const response = await getUserPointsInfo(user.value.userId, type, {
				pageNum: page,
				pageSize: pageSize.value
			})

			if (response.code === 200) {
				const newRecords = response.rows || []
				totalCount.value = response.total || 0

				if (reset) {
					pointsChangeRecords.value = newRecords
				} else {
					pointsChangeRecords.value = [...pointsChangeRecords.value, ...newRecords]
				}

				// 检查是否还有更多数据
				hasMore.value = pointsChangeRecords.value.length < totalCount.value
				currentPage.value = page
			}
		} catch (error) {
			console.error('获取积分记录失败:', error)
			uni.showToast({
				title: '获取积分记录失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	// 刷新用户信息
	const handleRefresh = async () => {
		await userStore.getInfo()
		user.value = userStore.user
		userAdditionalInfo.value = userStore.userAdditionalInfo
	}

	// 加载更多记录
	const handleLoadMore = () => {
		if (!loading.value && hasMore.value) {
			const nextPage = currentPage.value + 1
			fetchPointsHistory(nextPage, false, currentFilterType.value)
		}
	}

	// 刷新积分历史
	const handleRefreshHistory = () => {
		currentPage.value = 1
		isExpanded.value = false
		fetchPointsHistory(1, true, currentFilterType.value)
	}

	// 切换展开/收起状态
	const handleToggleExpand = () => {
		// 收起：重置为第一页数据
		isExpanded.value = false
		currentPage.value = 1
		fetchPointsHistory(1, true, currentFilterType.value)
	}

	// 处理筛选类型变化
	const handleFilterChange = (filterType : string) => {
		// 将前端筛选类型转换为后端类型
		let type = 1 // 默认全部
		if (filterType === 'income') {
			type = 2 // 收入
		} else if (filterType === 'expense') {
			type = 3 // 支出
		}

		currentFilterType.value = type
		currentPage.value = 1
		isExpanded.value = false
		fetchPointsHistory(1, true, type)
	}

	onMounted(() => {
		fetchPointsHistory(1, true, 1) // 默认加载全部记录
	})

	// 处理签到
	// 处理签到
	const handleCheckIn = async () => {
		try {
			const response = await userCheckIn()
			if (response.code === 200) {
				uni.showToast({
					title: response.msg || '签到成功',
					icon: 'success'
				})
				// 签到成功后刷新用户信息和积分记录
				await handleRefresh()
				handleRefreshHistory()
			} else {
				uni.showToast({
					title: response.msg || '签到失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('签到失败:', error)
			// 由于request工具已经通过toast显示了错误信息，这里不需要再次显示
			// 如果需要额外处理，可以在这里添加
		}
	}

	// 下拉刷新处理
	const onRefresh = async () => {
		refresherTriggered.value = true
		try {
			// 刷新用户信息
			await handleRefresh()
			// 刷新积分历史记录
			handleRefreshHistory()
			
			uni.showToast({
				title: '刷新成功',
				icon: 'success',
				duration: 1500
			})
		} catch (error) {
			console.error('刷新失败:', error)
			uni.showToast({
				title: '刷新失败',
				icon: 'none'
			})
		} finally {
			// 延迟结束刷新状态，确保用户能看到刷新动画
			setTimeout(() => {
				refresherTriggered.value = false
			}, 1000)
		}
	}

	// 刷新恢复处理
	const onRestore = () => {
		refresherTriggered.value = false
	}
</script>

<style lang="scss" scoped>
	.points-container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
		height: 100vh; /* 为scroll-view设置固定高度 */
	}
</style>